// store/user.js
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户类型：null(未登录), 'user'(普通用户), 'merchant'(商家)
    userType: null,
    userInfo: null,
    isLoggedIn: false,
    hasShownLoginPopup: false,
    token: null // 添加token字段，用于API鉴权
  }),
  
  actions: {
    // 设置已显示登录弹窗标记
    setLoginPopupShown() {
      this.hasShownLoginPopup = true;
      // 持久化存储
      uni.setStorageSync('hasShownLoginPopup', true);
    },
    
    // 登录
    login(type, info, token = null) {
      this.userType = type;
      this.userInfo = info;
      this.isLoggedIn = true;
      this.token = token;
      
      // 存储到本地
      uni.setStorageSync('userType', type);
      uni.setStorageSync('userInfo', JSON.stringify(info)); // 确保对象被正确序列化
      uni.setStorageSync('isLoggedIn', true);
      
      if (token) {
        uni.setStorageSync('token', token);
      }
      
      console.log('用户登录成功:', {
        type: this.userType,
        isLoggedIn: this.isLoggedIn,
        info: this.userInfo
      });
    },

    // 登出
    logout() {
      this.userType = null;
      this.userInfo = null;
      this.isLoggedIn = false;
      this.token = null;
      
      // 清除本地存储
      uni.removeStorageSync('userType');
      uni.removeStorageSync('userInfo');
      uni.removeStorageSync('isLoggedIn');
      uni.removeStorageSync('token');
    },

    // 初始化用户状态
    initUserState() {
      // 从本地存储读取登录状态
      const storedIsLoggedIn = uni.getStorageSync('isLoggedIn');
      
      if (storedIsLoggedIn) {
        this.userType = uni.getStorageSync('userType');
        this.token = uni.getStorageSync('token');
        
        try {
          const userInfoStr = uni.getStorageSync('userInfo');
          this.userInfo = userInfoStr ? JSON.parse(userInfoStr) : null;
        } catch (e) {
          console.error('解析用户信息失败:', e);
          this.userInfo = null;
        }
        this.isLoggedIn = true;
      } else {
        this.userType = null; // 修改：未登录时设为null，而不是默认为'user'
        this.isLoggedIn = false;
      }
      
      // 读取登录弹窗显示状态
      this.hasShownLoginPopup = !!uni.getStorageSync('hasShownLoginPopup');
      console.log('初始化用户状态:', {
        isLoggedIn: this.isLoggedIn,
        userType: this.userType,
        hasShownLoginPopup: this.hasShownLoginPopup
      });
    },

    // 判断是否为商家
    isMerchant() {
      return this.userType === 'merchant';
    },
    
    // 重置登录弹窗状态（用于测试）
    resetLoginPopupState() {
      this.hasShownLoginPopup = false;
      uni.removeStorageSync('hasShownLoginPopup');
    },
    
    // 更新用户信息
    updateUserInfo(info) {
      this.userInfo = { ...this.userInfo, ...info };
      uni.setStorageSync('userInfo', JSON.stringify(this.userInfo));
    }
  }
});